package school30.io.memory;

import school30.io.*;

public class MemoryFileWriter extends FileWriter{
    private MemoryFileStorage storage;
    private File path;
    private byte[] buf;
    private int n;

    public MemoryFileWriter(MemoryFileStorage st, File path, int bufsize)
    {
        this.storage = st;
        this.path = path;
        this.buf = new byte[bufsize];
        n = 0;
    }

    public int write(byte[] b) {
        for (int i = 0; i < b.length; i++)
        {
            buf[n] = b[i];
            n++;
            if (n == buf.length)
                flush();
        }
        return 0;
    }

    public void close() {
        flush();
    }

    public void flush()
    {
        byte[] c = storage.readFile(path);
        byte[] k;
        if (c != null)
          k = new byte[c.length + n];
        else
        {
            k = new byte[n];
            c = new byte[0];
        }
        for (int i = c.length; i < k.length; i++)
            k[i] = buf[i - c.length];
        storage.saveFile(k, path);
        n = 0;
    }
}
